/*
 * Created on Jun 22, 2011 by frederico.concrete for gerarCodigoBarras
 * 
 * Copyright M4U Solucoes 2001-2011
 */
package br.fbc.codigodebarras;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

public class GerarCodigoDeBarras {

	private static String RAIZ = "/home/qrforlife/webapps/";

	public static File getFileCodigoBarras(String nome, String link)
			throws WriterException, IOException {

		int width = 400;
		int height = 300;

		String imageFormat = "png"; // could be "gif", "tiff", "jpeg"

		File file = getFile(nome.replaceAll(" ", ""));

		FileOutputStream fileOutputStream = new FileOutputStream(file);
		BitMatrix bitMatrix = new QRCodeWriter().encode(link,
				BarcodeFormat.QR_CODE, width, height);
		MatrixToImageWriter.writeToStream(bitMatrix, imageFormat,
				fileOutputStream);

		return file;

	}

	private static File getFile(String nome) {

		File file = new File(RAIZ + "imagens/" + nome + ".png");

		System.out.println(file.getAbsoluteFile());
		if (!file.canRead()) {
			file = new File(RAIZ + "ROOT/imagens/" + nome + ".png");
			System.out.println(file.getAbsoluteFile());
		}
		if (!file.canRead()) {
			file = new File(nome + ".png");
			System.out.println(file.getAbsoluteFile());
		}
		
		if (!file.canRead()) {
			file = new File(RAIZ + nome + ".png");
			System.out.println(file.getAbsoluteFile());
		}

		return file;
	}
}
